//
//  BuyList.m
//  忘不了
//
//  Created by rimi on 16/7/12.
//  Copyright © 2016年 handuan. All rights reserved.
//

#import "BuyList.h"
#import "SDAutoLayout.h"
#import "BaseRequest.h"
#import "BaseRequest+Buy.h"
#import "CustomBuylistCell.h"
#import "UIColor+Expand.h"
#import "CustomBuylistCell.h"
#import "UserModel.h"
#import "addMoneyViewController.h"
#import "LoginViewController.h"
#import "UMSocial.h"
@interface BuyList ()<UITableViewDelegate,UITableViewDataSource,CustomBuylistDelegate,UMSocialUIDelegate>
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)UITableView *buyTableView;
@property (nonatomic, strong)NSMutableArray *buyDataSource;
@property (nonatomic, strong)UILabel *noBuy;
@property (nonatomic, strong)UIButton *menuButton;
//如果已购没有东西，显示未购买label
- (void)isBuyDOne;
//打开菜单
- (void)openMenu:(UIButton *)sender;
//进入详情
- (void)toDetail:(UIButton *)sender;
@end
@implementation BuyList
- (void)viewDidLoad{
    [super viewDidLoad];
    [self initializeUserInterface];
}
- (void)viewWillAppear:(BOOL)animated{
    [self initializeDataSource];
    [self.buyTableView reloadData];
    [self.tableView reloadData];
    [self isBuyDOne];
}
- (void)initializeDataSource{
    NSArray *buyArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"buyDoneList"];
    self.buyDataSource = [[NSMutableArray alloc]initWithArray:buyArray];
    NSArray *array = [[NSUserDefaults standardUserDefaults] objectForKey:@"selectList"];
    self.dataSource = [[NSMutableArray alloc]initWithArray:array];
    NSMutableArray *flagArr = [NSMutableArray array];
        for (NSInteger index = 0; index < self.dataSource.count; index ++) {
            for (NSInteger index1 = self.dataSource.count - 1; index1 > index; index1 --) {
                if ([self.dataSource[index] isEqualToString:self.dataSource[index1]]) {
//                    [flagArr addObject:self.dataSource[index1]];
                    [self.dataSource removeObjectAtIndex:index1];
                }
            }
        }
    NSLog(@"%@",self.dataSource);
    NSLog(@"=======%@",flagArr);
    
    NSLog(@"%@",self.dataSource);
}
- (void)initializeUserInterface{
//    [UMSocialData defaultData].extConfig.qqData.title = @"QQ分享title";
//    [UMSocialData defaultData].extConfig.qzoneData.title = @"Qzone分享title";
    self.title = @"购物清单";
    self.view.backgroundColor = [UIColor whiteColor];
    UIBarButtonItem *menu = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"分享"] style:UIBarButtonItemStyleDone target:self action:@selector(share:)];
    self.navigationItem.rightBarButtonItem = menu;
    //未购tableView
    self.tableView = [[UITableView alloc]init];
    self.tableView.delegate = self;
    //    UIImageView *backImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"s"]];
    //    [self.tableView setBackgroundView:backImageView];
    self.tableView.dataSource = self;
    self.tableView.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds) * 0.5);
    //注册cell
    [self.tableView registerClass:[CustomBuylistCell class] forCellReuseIdentifier:@"cell"];
    [self.view addSubview:self.tableView];
    //中间的标题栏
    UIView *titleView = [[UIView alloc]init];
    titleView.backgroundColor = [UIColor redColor];
    [self.view addSubview:titleView];
    titleView.sd_layout
    .topSpaceToView(self.tableView,0)
    .leftSpaceToView(self.view,0)
    .widthIs(CGRectGetWidth(self.view.bounds))
    .heightIs(CGRectGetHeight(self.view.bounds) * 0.05);
    UIImageView *image = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"buyDone"]];
    [titleView addSubview:image];
    image.sd_layout
    .topSpaceToView(titleView,0)
    .leftSpaceToView(titleView,0)
    .bottomSpaceToView(titleView,0)
    .rightSpaceToView(titleView,0);
    UILabel *buyDoneLabel = [[UILabel alloc]init];
    buyDoneLabel.text = @"已购↓";
    buyDoneLabel.font = [UIFont fontWithName:@"Helvetica-BoldOblique" size:20];
    buyDoneLabel.textAlignment = NSTextAlignmentCenter;
    [titleView addSubview:buyDoneLabel];
    buyDoneLabel.sd_layout
    .topSpaceToView(titleView,0)
    .bottomSpaceToView(titleView,0)
    .widthIs(CGRectGetWidth(titleView.bounds) * 0.5)
    .centerXEqualToView(titleView);
    
    //已购tableView
    self.buyTableView = [[UITableView alloc]init];
    self.buyTableView.backgroundColor = [UIColor whiteColor];
    self.buyTableView.delegate = self;
    self.buyTableView.dataSource = self;
    //注册cell
    [self.buyTableView registerClass:[CustomBuylistCell class] forCellReuseIdentifier:@"cell"];
    [self.view addSubview:self.buyTableView];
    self.buyTableView.sd_layout
    .topSpaceToView(titleView,0)
    .leftSpaceToView(self.view,0)
    .bottomSpaceToView(self.view,0)
    .rightSpaceToView(self.view,0);
    
    //没有已购
    self.noBuy = [[UILabel alloc]init];
    self.noBuy.text = @"您还没有购买物品";
    self.noBuy.textColor = [UIColor colorWithRed:1.0 green:0.0544 blue:0.134 alpha:1.0];
    self.noBuy.font = [UIFont fontWithName:@"Helvetica-BoldOblique" size:15];
    self.noBuy.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.noBuy];
    self.noBuy.sd_layout
    .centerYEqualToView(self.buyTableView)
    .centerXEqualToView(self.view)
    .widthIs(CGRectGetWidth(self.view.bounds) * 0.6)
    .heightIs(CGRectGetHeight(self.view.bounds) * 0.1);
    //菜单按钮
    self.menuButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.menuButton addTarget:self action:@selector(openMenu:) forControlEvents:UIControlEventTouchUpInside];
    [self.menuButton setBackgroundImage:[UIImage imageNamed:@"按钮"] forState:UIControlStateNormal];
    [self.menuButton setTitle:@"操作" forState:UIControlStateNormal];
    [self.menuButton setTitleColor:[UIColor colorWithRed:0.062 green:0.5349 blue:1.0 alpha:1.0] forState:UIControlStateNormal];
    [self.view addSubview:self.menuButton];
    self.menuButton.sd_layout
    .bottomSpaceToView(self.view,50)
    .centerXEqualToView(self.view)
    .widthIs(CGRectGetWidth(self.view.bounds) * 0.2)
    .heightEqualToWidth();
    NSArray *buttonName = @[@"入账",@"清空"];
    for (NSInteger index = 0; index < 2; index ++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.tag = 1200 + index;
        [button setTitle:buttonName[index] forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageNamed:@"按钮"] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor colorWithRed:0.062 green:0.5349 blue:1.0 alpha:1.0] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(toDetail:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button];
        [self.view bringSubviewToFront:self.menuButton];
        button.sd_layout
        .centerXEqualToView(self.menuButton)
        .centerYEqualToView(self.menuButton)
        .widthRatioToView(self.menuButton,1)
        .heightEqualToWidth();
    }
}

- (void)share:(UIBarButtonItem *)sender{
    
    [UMSocialData defaultData].extConfig.qzoneData.url = @"http://baidu.com";
//    [UMSocialData defaultData].extConfig.qzoneData.title = @"Qzone分享title";
    
    [UMSocialData defaultData].extConfig.qqData.title = @"QQ分享title";
    [UMSocialData defaultData].extConfig.qzoneData.title = @"Qzone分享title";
//    [[UMSocialData defaultData].urlResource setResourceType:UMSocialUrlResourceTypeImage url:@"http://img0.imgtn.bdimg.com/it/u=201581813,2440236979&fm=206&gp=0.jpg"];
    NSURL *url = [NSURL URLWithString:@"http://img0.imgtn.bdimg.com/it/u=201581813,2440236979&fm=206&gp=0.jpg"];
    NSData *data = [NSData dataWithContentsOfURL:url];
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"579332bee0f55a9db70023f5"
                                      shareText:@"ggfgdsd"
                                     shareImage:[UIImage imageWithData:data]
                                shareToSnsNames:@[UMShareToQzone,UMShareToQQ]
                                       delegate:self];
//    [UMSocialSnsService presentSnsIconSheetView:self
//                                         appKey:@"579332bee0f55a9db70023f5"
//                                      shareText:@"友盟社会化分享让您快速实现分享等社会化功能，http://umeng.com/social"
//                                     shareImage:[UIImage imageNamed:@"icon.png"]
//                                shareToSnsNames:@[UMShareToQQ,UMShareToQzone]
//                                       delegate:self];
}
//- (UIView *)shareView{
//    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(CGRectGetMaxY(self.view.frame), 64, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds) / 8)];
//    view.backgroundColor = [UIColor colorWithRed:1.0 green:0.7197 blue:0.6194 alpha:1.0];
//    for (NSInteger index = 0; index < 2; index ++) {
//        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//        [button setImage:[UIImage imageNamed:@"确定"] forState:UIControlStateNormal];
//        button.bounds = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds) / 6, view.bounds.size.height);
//        button.tag = index + 9000;
//        button.center = CGPointMake(index * button.bounds.size.width + button.bounds.size.width / 2, 0);
//        [button addTarget:self action:@selector(shareButtonPresent:) forControlEvents:UIControlEventTouchUpInside];
//        [view addSubview:button];
//    }
//    return view;
//}
//- (void)shareButtonPresent:(UIButton *)sender{
//    if (sender.tag == 9000) {
//        
//    }else{
//        
//    }
//}
- (void)toDetail:(UIButton *)sender{
    UserModel *user = [UserModel shareUserModel];
    if (sender.tag == 1200) {
        if (user.isLogin) {
            addMoneyViewController *moneyVC = [[addMoneyViewController alloc]init];
            [self.navigationController pushViewController:moneyVC animated:YES];
        }else{
            LoginViewController *LVC = [[LoginViewController alloc]init];
            [self.navigationController pushViewController:LVC animated:YES];
            
        }
        
    }
    if (sender.tag == 1201) {
        [self.dataSource removeAllObjects];
        [self.buyDataSource removeAllObjects];
        [self.tableView reloadData];
        [self.buyTableView reloadData];
        [[NSUserDefaults standardUserDefaults] setObject:self.buyDataSource forKey:@"buyDoneList"];
        [[NSUserDefaults  standardUserDefaults] setObject:self.dataSource forKey:@"selectList"];
        [self isBuyDOne];
    }
}
- (void)openMenu:(UIButton *)sender{
    UIButton *toCount = [self.view viewWithTag:1200];
    UIButton *clearList = [self.view viewWithTag:1201];
    sender.selected = !sender.selected;
    if (sender.selected) {
        [UIView animateWithDuration:0.2 animations:^{
            toCount.center = CGPointMake(toCount.centerX - toCount.width * 1.5, toCount.centerY);
            clearList.center = CGPointMake(clearList.centerX + toCount.width * 1.5, clearList.centerY);
        }];
    }else{
        [UIView animateWithDuration:0.2 animations:^{
            toCount.center = CGPointMake(self.menuButton.centerX, self.menuButton.centerY);
            clearList.center = CGPointMake(self.menuButton.centerX, self.menuButton.centerY);
        }];
    }
}
- (void)isBuyDOne{
    if (self.buyDataSource.count == 0) {
        self.noBuy.hidden = NO;
        self.buyTableView.hidden = YES;
    }else{
        self.noBuy.hidden = YES;
        self.buyTableView.hidden = NO;
    }
}
#pragma mark - UITableViewDelegate

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //取消选中状态
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (void)editAction:(UIBarButtonItem *)sender{
    [self.tableView setEditing:!self.tableView.editing animated:YES];
    [self.buyTableView setEditing:!self.buyTableView.editing animated:YES];
}
//配置删除按钮的title
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}
//提交编辑状态
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        if (tableView == self.tableView) {
            //1.删除数据源
            [self.dataSource removeObjectAtIndex:indexPath.row];
            [[NSUserDefaults standardUserDefaults] setObject:self.dataSource forKey:@"selectList"];
        }else{
            [self.buyDataSource removeObjectAtIndex:indexPath.row];
            [[NSUserDefaults standardUserDefaults] setObject:self.buyDataSource forKey:@"buyDoneList"];
            [self isBuyDOne];
        }
        
        //2.删除表格行视图
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationBottom];
    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == self.tableView) {
        return self.dataSource.count;
    }else{
        return self.buyDataSource.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CustomBuylistCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    cell.colorView.backgroundColor = [UIColor specialRandomColor];
    if (tableView == self.tableView) {
        [cell.deleteButton setImage:[UIImage imageNamed:@"下"] forState:UIControlStateNormal];
        cell.flag = 100 + indexPath.row;
        cell.name.text = self.dataSource[indexPath.row];
        NSLog(@"%ld",(long)cell.flag);
    }else{
        [cell.deleteButton setImage:[UIImage imageNamed:@"上"] forState:UIControlStateNormal];
        cell.flag = 200 + indexPath.row;
        cell.name.text = self.buyDataSource[indexPath.row];
        cell.name.textColor = [UIColor colorWithRed:0.6991 green:0.6991 blue:0.6991 alpha:1.0];
    }
    cell.delegate = self;
    return cell;
}

#pragma mark - CustomBuylistDelegate
- (void)customBuylistDelegate:(CustomBuylistCell *)cell{
    //当购物清单为0时
    if (cell.flag >= 200) {
        //移动到上面的tableview
        NSString *object = self.buyDataSource[cell.flag - 200];
        [self.dataSource addObject:object];
        [self.buyDataSource removeObject:object];
    } else {
        NSString *object = self.dataSource[cell.flag - 100];
        [self.buyDataSource addObject:object];
        NSLog(@"%@",self.buyDataSource);
        [self.dataSource removeObject:object];
    }
    [[NSUserDefaults standardUserDefaults] setObject:self.dataSource forKey:@"selectList"];
    [[NSUserDefaults standardUserDefaults] setObject:self.buyDataSource forKey:@"buyDoneList"];
    [self.buyTableView reloadData];
    [self.tableView reloadData];
    [self isBuyDOne];
    
    //    if (self.dataSource.count == 0) {
    //        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示：" message:@"确定您的物品已经购买齐全？" preferredStyle:UIAlertControllerStyleAlert];
    //        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    //        UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    //            [self.buyDataSource removeAllObjects];
    //            [[NSUserDefaults standardUserDefaults] setObject:self.buyDataSource forKey:@"buyDoneList"];
    //            [self.buyTableView reloadData];
    //        }];
    //        [alert addAction:cancel];
    //        [alert addAction:sure];
    //        [self presentViewController:alert animated:YES completion:nil];
    //        [self.buyDataSource removeAllObjects];
    //    }
    
}
@end